package com.xzh.controller;

import com.xzh.constant.RedisConstants;
import com.xzh.util.AliOSSUtil;
import com.xzh.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@RequestMapping("/api/v1/users")
public class UploadController {
    private RedisTemplate redisTemplate;

    @Autowired
    public UploadController(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @RequestMapping("/avatar")
    public JsonResult<?> upload(@RequestParam(value = "file", required = false) MultipartFile file) {
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            return JsonResult.fail("请选择要上传的文件");
        }

        // 553dd137eabe4f6a947bc8d8d92afa7f
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 1.png
        String filename = file.getOriginalFilename();
        if (filename == null || filename.isEmpty()) {
            return JsonResult.fail("文件名不能为空");
        }

        String extension = "";
        // 安全地获取文件扩展名
        int lastIndex = filename.lastIndexOf(".");
        if (lastIndex > 0) {
            extension = filename.substring(lastIndex);
        }

        String newFileName = uuid + extension;
        //上传到阿里云
        String url = "";
        try {
            url = AliOSSUtil.uploadFile(newFileName, file.getInputStream());
        } catch (Exception e) {
            return JsonResult.fail("文件上传失败: " + e.getMessage());
        }

        //将上传的图片保存到redis中
        redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE, url);

        return JsonResult.success(url);
    }
}
